import React, { useEffect, useState } from 'react';
import { Select, Pagination, Spin } from 'antd';
import useStore from '../../../components/useStore';
import request from '../../../untils/request';

const { Option } = Select;

const AddStation = () => {
    const { collapsed } = useStore();
    const [stationName, setStationName] = useState('');
    const [phone, setPhone] = useState(''); // 负责人联系方式
    const [city, setCity] = useState(''); // 站点所在地
    const [message, setMessage] = useState('');
    const [customerList, setCustomerList] = useState([]); // 客户信息列表
    const [selectedCustomerId, setSelectedCustomerId] = useState(null); // 选中的客户ID
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [loadingCustomers, setLoadingCustomers] = useState(false); // 加载客户时的加载状态
    
    // 分页相关状态
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [totalCustomers, setTotalCustomers] = useState(0); // 客户总数
    const [searchName, setSearchName] = useState(''); // 客户搜索关键词

    // 验证电话号码格式（11位数字）
    const validatePhone = (value) => {
        const reg = /^1\d{10}$/;
        return reg.test(value);
    };

    // 获取客户列表数据（带分页）
    const fetchCustomers = () => {
        const offset = (currentPage - 1) * pageSize;
        setLoadingCustomers(true);
        request("/admin/customer/getCustomers", {
            method: "POST",
            body: {
                pageSize,
                offset,
                name: searchName  // 传递查询条件
            }
        }).then((res) => {
            setLoadingCustomers(false);
            if (res.code === 200) {
                setCustomerList(res.data || []);
                setTotalCustomers(res.total || 0);
            } else {
                setMessage('获取客户列表失败');
            }
        }).catch(() => {
            setLoadingCustomers(false);
            setMessage('获取客户列表时发生错误');
        });
    };

    // 初始加载和分页参数变化时获取客户列表
    useEffect(() => {
        fetchCustomers();
    }, [currentPage, pageSize, searchName]);

    // 处理分页变化
    const handlePageChange = (page, pageSize) => {
        setCurrentPage(page);
        setPageSize(pageSize);
    };

    // 处理客户搜索
    const handleCustomerSearch = (value) => {
        setSearchName(value);
        setCurrentPage(1); // 搜索时重置到第一页
    };

    // 处理表单提交
    const handleSubmit = async (e) => {
        e.preventDefault();
        
        // 验证
        if (!stationName.trim()) {
            setMessage('请输入站点名称');
            return;
        }
        
        if (!selectedCustomerId) {
            setMessage('请选择所属客户');
            return;
        }

        if (!phone.trim()) {
            setMessage('请输入负责人联系方式');
            return;
        }

        if (!validatePhone(phone.trim())) {
            setMessage('请输入有效的11位手机号码');
            return;
        }

        if (!city.trim()) {
            setMessage('请输入站点所在地');
            return;
        }
        
        try {
            setIsSubmitting(true);
            setMessage('');
            
            // 发送请求到后端
            await request("/admin/station/add",{
                method:"POST",
                body:{
                    name: stationName.trim(),
                    customer_id: selectedCustomerId,
                    phone: phone.trim(),  // 添加负责人联系方式
                    city: city.trim()     // 添加站点所在地
                }
            }).then((res)=>{
                if (res.code === 200) {
                    setMessage('站点添加成功！');
                    // 清空所有输入框
                    setStationName('');
                    setPhone('');
                    setCity('');
                    setSelectedCustomerId(null);
                    // 3秒后清除成功提示
                    setTimeout(() => setMessage(''), 3000);
                } else {
                    setMessage(res.msg || '添加失败，请重试');
                }
            })
        } catch (error) {
            setMessage('网络错误，请稍后重试');
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <div style={{    
            height: "94%", 
            backgroundColor: `#F1F1F1`,
            right: "1%",
            top: "4vh",
            overflow: "auto",
            width: collapsed ? "94%" : "84%", 
            position: "absolute",  
            color: "white", 
            fontSize: "0.8rem"
        }}>
            <div style={styles.kshcontainer}>
                <div style={styles.header}>
                    <h2>新增站点</h2>
                </div>
                
                <form onSubmit={handleSubmit} style={styles.formContainer}>
                    <div style={styles.formGroup}>
                        <label style={styles.label}>
                            站点名称 
                            <span style={styles.required}>*</span>
                        </label>
                        <input
                            type="text"
                            value={stationName}
                            onChange={(e) => setStationName(e.target.value)}
                            style={styles.input}
                            placeholder="请输入站点名称"
                            disabled={isSubmitting}
                            maxLength={50}
                        />
                    </div>
                    
                    <div style={styles.formGroup}>
                        <label style={styles.label}>
                            所属客户 
                            <span style={styles.required}>*</span>
                        </label>
                        <div>
                            <Select
                                showSearch
                                placeholder="请选择客户"
                                style={{ width: '100%' }}
                                value={selectedCustomerId}
                                onChange={setSelectedCustomerId}
                                onSearch={handleCustomerSearch}
                                filterOption={false}
                                disabled={isSubmitting || loadingCustomers}
                                notFoundContent={loadingCustomers ? <Spin size="small" /> : null}
                            >
                                {customerList.map(customer => (
                                    <Option key={customer.id} value={customer.id}>
                                        {customer.name}
                                    </Option>
                                ))}
                            </Select>
                            
                            {/* 分页控件 */}
                            <div style={styles.paginationContainer}>
                                <Pagination
                                    current={currentPage}
                                    pageSize={pageSize}
                                    total={totalCustomers}
                                    onChange={handlePageChange}
                                    showSizeChanger
                                    showQuickJumper
                                    showTotal={(total) => `共 ${total} 个客户`}
                                    disabled={loadingCustomers || isSubmitting}
                                />
                            </div>
                        </div>
                    </div>

                    {/* 新增：负责人联系方式 */}
                    <div style={styles.formGroup}>
                        <label style={styles.label}>
                            负责人联系方式 
                            <span style={styles.required}>*</span>
                        </label>
                        <input
                            type="text"
                            value={phone}
                            onChange={(e) => setPhone(e.target.value)}
                            style={styles.input}
                            placeholder="请输入11位手机号码"
                            disabled={isSubmitting}
                            maxLength={11}
                            // 只允许输入数字
                            onInput={(e) => e.target.value = e.target.value.replace(/[^\d]/g, '')}
                        />
                    </div>

                    {/* 新增：站点所在地 */}
                    <div style={styles.formGroup}>
                        <label style={styles.label}>
                            站点所在地 
                            <span style={styles.required}>*</span>
                        </label>
                        <input
                            type="text"
                            value={city}
                            onChange={(e) => setCity(e.target.value)}
                            style={styles.input}
                            placeholder="请输入站点所在地"
                            disabled={isSubmitting}
                            maxLength={50}
                        />
                    </div>
                    
                    {message && (
                        <div style={message.includes('成功') ? styles.successMsg : styles.errorMsg}>
                            {message}
                        </div>
                    )}
                    
                    <div style={styles.buttonGroup}>
                        <button 
                            type="submit" 
                            style={styles.submitBtn}
                            disabled={isSubmitting}
                        >
                            {isSubmitting ? '提交中...' : '提交'}
                        </button>
                        <button 
                            type="button" 
                            style={styles.cancelBtn}
                            onClick={() => {
                                setStationName('');
                                setPhone('');
                                setCity('');
                                setSelectedCustomerId(null);
                                setMessage('');
                            }}
                            disabled={isSubmitting}
                        >
                            取消
                        </button>
                    </div>
                </form>
            </div>
        </div>
    )
}

export default AddStation

var styles = {
    kshcontainer: {
        width: "98%", 
        height: "95%", 
        position: "absolute", 
        top: "3%", 
        left: "1%", 
        backgroundColor: "white", 
        color: "black",
        borderRadius: "10px",
        boxShadow: "0 2px 8px rgba(0,0,0,0.1)"
    },
    header: {
        padding: "1rem 2%",
        borderBottom: "1px solid #eee",
        marginBottom: "1.5rem"
    },
    formContainer: {
        width: "96%",
        margin: "0 auto",
        padding: "0 2%"
    },
    formGroup: {
        marginBottom: "1.5rem"
    },
    label: {
        display: "block",
        marginBottom: "0.5rem",
        fontSize: "0.9rem",
        color: "#333"
    },
    required: {
        color: "#ff4d4f"
    },
    input: {
        width: "100%",
        padding: "8px 12px",
        borderRadius: "4px",
        border: "1px solid #d9d9d9",
        fontSize: "0.9rem",
        boxSizing: "border-box"
    },
    successMsg: {
        color: "#52c41a",
        padding: "8px 0",
        fontSize: "0.85rem",
        marginBottom: "1rem"
    },
    errorMsg: {
        color: "#ff4d4f",
        padding: "8px 0",
        fontSize: "0.85rem",
        marginBottom: "1rem"
    },
    buttonGroup: {
        display: "flex",
        gap: "1rem",
        marginTop: "2rem"
    },
    submitBtn: {
        padding: "8px 16px",
        backgroundColor: "#1890ff",
        color: "white",
        border: "none",
        borderRadius: "4px",
        cursor: "pointer",
        fontSize: "0.9rem"
    },
    cancelBtn: {
        padding: "8px 16px",
        backgroundColor: "#f5f5f5",
        color: "#333",
        border: "1px solid #d9d9d9",
        borderRadius: "4px",
        cursor: "pointer",
        fontSize: "0.9rem"
    },
    paginationContainer: {
        marginTop: 10,
        textAlign: 'right'
    }
}
